package com.liu.stockmarket.repository.database.dao

import androidx.room.*
import com.liu.stockmarket.repository.database.entity.StockEntity
import com.liu.stockmarket.repository.database.entity.TransactionRecordEntity
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import java.time.LocalDate


@Dao
abstract class TransactionRecordDao {
    @Insert
    abstract suspend fun save(transactionRecordEntity: TransactionRecordEntity)

    /**
     * 查询某个股票的交易记录
     */
    @Query(value = "select * from transaction_record where stock_id= :stockId")
    abstract fun queryByStockId(stockId: Long): Flow<List<TransactionRecordEntity>>

    /**
     * 当观察的数据发生变化才会通知
     */
    fun queryByStockIdDistinctUntilChanged(stockId: Long) =
        queryByStockId(stockId).distinctUntilChanged()


    /**
     * 查询某日的交易记录
     */
    @Query(value = "select * from transaction_record where transaction_date = :date")
    abstract suspend fun queryTodayTransactionRecord(date: LocalDate):List<TransactionRecordEntity>

    @Query(value = "select * from transaction_record where stock_id =:stockId and transaction_date = :date")
    abstract suspend fun queryTodayTransactionRecordByStockId(stockId: Long,date: LocalDate):List<TransactionRecordEntity>

    /**
     * 删除股票的交易记录
     */
    @Query(value = "delete from transaction_record where stock_id = :stockId")
    abstract suspend fun deleteByStockId(stockId: Long): Int


    @Query(value = "select * from transaction_record")
    abstract fun queryAllFlow(): Flow<List<TransactionRecordEntity>>

    @Query(value = "select * from transaction_record")
    abstract suspend fun queryAll(): List<TransactionRecordEntity>

    @Insert
    abstract suspend fun saveAll(transactionRecordEntitys: List<TransactionRecordEntity>)

    @Query("delete from transaction_record")
    abstract suspend fun deleteAll()


    /**
     * 先删除数据，后更新
     */
    suspend fun deleteAllForSaveAll(transactionRecordEntitys: List<TransactionRecordEntity>) {
        deleteAll()
        saveAll(transactionRecordEntitys)
    }
}